package rpc

import (
	"fmt"

	"gitee.com/go-course/go8/projects/devcloud/mcenter/client/rpc"
	"github.com/infraboard/mcube/logger"
	"github.com/infraboard/mcube/logger/zap"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"

	"gitee.com/go-course/go8/projects/devcloud/maudit/apps/operate"
	"gitee.com/go-course/go8/projects/devcloud/maudit/client/rpc/resolver"
)

// NewClient 需要认证, 需要配置client_id 和 client_secret
// 直接使用mcenter的config对象
func NewClient(conf *rpc.Config) (*ClientSet, error) {
	zap.DevelopmentSetup()
	log := zap.L()

	resolver.SetAddr("maudit", []string{"127.0.0.1:19020", "127.0.0.1:19010"})
	conn, err := grpc.Dial(
		// staic:///maudit --> []string{"127.0.0.1:19010"}
		fmt.Sprintf("%s:///maudit", resolver.StaticScheme),
		grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithPerRPCCredentials(conf.Credentials()),
		// 配置负载均衡策略
		grpc.WithDefaultServiceConfig(`{"loadBalancingConfig": [{"round_robin":{}}]}`), // This sets the initial balancing policy.
	)
	if err != nil {
		return nil, err
	}

	return &ClientSet{
		conn: conn,
		log:  log,
	}, nil
}

// Client 审计中心客户端
type ClientSet struct {
	conn *grpc.ClientConn
	log  logger.Logger
}

func (c *ClientSet) Operate() operate.RPCClient {
	return operate.NewRPCClient(c.conn)
}
